#pragma once
#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <cstring>
#include <assert.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
using namespace std;

#define PATHNAME "."
#define PROJID 0x0001

const int gsize = 4096;

key_t GetKey()
{
    key_t k = ftok(PATHNAME, PROJID);

    if (k == -1)
    {
        cerr << errno << " : " << strerror(errno) << endl;
        exit(1);
    }
    return k;
}

string toHex(int x)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%x", x);
    return buffer;
}

int creatShmHelper(key_t k, int size, int flag)
{
    int shmid = shmget(k, gsize, flag);
    if (shmid == -1)
    {
        cerr << errno << " : " << strerror(errno) << endl;
        exit(2);
    }
    return shmid;
}

int creatShm(key_t k, int size)
{
    umask(0);
    return creatShmHelper(k, size, IPC_CREAT | IPC_EXCL | 0666);
}

int getShm(key_t k, int size)
{
    return creatShmHelper(k, size, IPC_CREAT);
}

char* attachShm(int shmid)
{
    char* start = (char*)shmat(shmid, nullptr, 0);
    return start;
}

void detachShm(char* start)
{
    int n = shmdt(start);
    assert(n != -1);
    (void)n;
}

void delShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    assert(n != -1);
    (void)n;
}

// class Init()
// {
// public:
//     Init()
//     {
//         //
//     }
// }

#endif